package com.codebase.zookeeper.zk;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * 创建一个节点，有两种方式 同步和异步
 */
public class CreateNode implements Watcher{

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    /**
     * 同步方式创建节点
     */
    @Test
    public void test() throws Exception{
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateNode());
        countDownLatch.await();

        //创建一个开发的临时顺序节点
        String path1 = zooKeeper.create("/root_path1", "path1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(path1);
        String path2 = zooKeeper.create("/root_path2", "path2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(path2);
    }


    /**
     * 异步方式创建节点
     */
    @Test
    public void test1() throws Exception{
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateNode());
        countDownLatch.await();

        zooKeeper.create("/root_path1", "path1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,new AsynCallBack(), "想要传递的参数");

        Thread.sleep(4000);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            countDownLatch.countDown();
        }
    }
}

/**
 * 异步接收通知结果
 */
class AsynCallBack implements AsyncCallback.StringCallback{

    @Override
    public void processResult(int i, String s, Object o, String s1) {
        System.out.println("状态码:" +  i);
        System.out.println("path:" + s);
        System.out.println("ctx:" + o);
        System.out.println("服务器上节点的名字" + s1 );
    }
}
